package com.joker.demo.admin.router.impl;

import com.joker.demo.admin.router.ExecutorRouter;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 最近最久未使用（LRU）路由策略
 * @author : feixiang.li
 * @since : 2025-07-29 17:31
 */
public class RecentlyLeastUsedExecutorRouter implements ExecutorRouter {
    
    // 记录每个地址的最后使用时间
    private static final Map<String, Long> lastUsedTime = new ConcurrentHashMap<>();
    
    @Override
    public String route(String jobId, List<String> addressList) {
        if (addressList == null || addressList.isEmpty()) {
            return null;
        }
        
        // 初始化未记录的地址
        for (String address : addressList) {
            lastUsedTime.putIfAbsent(address, 0L);
        }
        
        // 找到最久未使用的地址
        String leastRecentlyUsedAddress = null;
        long oldestTime = Long.MAX_VALUE;
        
        for (String address : addressList) {
            Long lastUsed = lastUsedTime.get(address);
            if (lastUsed != null && lastUsed < oldestTime) {
                oldestTime = lastUsed;
                leastRecentlyUsedAddress = address;
            }
        }
        
        // 更新选中地址的最后使用时间
        if (leastRecentlyUsedAddress != null) {
            lastUsedTime.put(leastRecentlyUsedAddress, System.currentTimeMillis());
        }
        
        return leastRecentlyUsedAddress;
    }
} 